package com.snow.useviewdemo.function.eventtouch

import android.R
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup


/**
 * Created by zhaoyingtao
 * Date: 2021/9/9
 * Describe:
 */
class EventDeliveryLayout : ViewGroup {
    constructor(context: Context) : super(context)
    constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        Log.e("eventSnow", "==EventDeliveryLayout===dispatchTouchEvent=====${ev?.action}")
        return super.dispatchTouchEvent(ev)
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        Log.e("eventSnow", "==EventDeliveryLayout===onTouchEvent=====${event?.action}")
        return super.onTouchEvent(event)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        Log.e("eventSnow", "==EventDeliveryLayout===onInterceptTouchEvent=====${ev?.action}")
        return super.onInterceptTouchEvent(ev)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        // 计算出所有的childView的宽和高
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        //测量并保存layout的宽高(使用getDefaultSize时，wrap_content和match_perent都是填充屏幕)
        //稍后会重新写这个方法，能达到wrap_content的效果
        setMeasuredDimension(getDefaultSize(suggestedMinimumWidth, widthMeasureSpec),
                getDefaultSize(suggestedMinimumHeight, heightMeasureSpec));
    }
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val count = childCount
        var childMeasureWidth = 0
        var childMeasureHeight = 0
        var layoutWidth = 0 // 容器已经占据的宽度
        var layoutHeight = 0 // 容器已经占据的宽度
        var maxChildHeight = 0 //一行中子控件最高的高度，用于决定下一行高度应该在目前基础上累加多少
Log.e("eventSnow","===EventDeliveryLayout===onLayout==$count")
        for (i in 0 until count) {
            val child: View = getChildAt(i)
            //注意此处不能使用getWidth和getHeight，这两个方法必须在onLayout执行完，才能正确获取宽高
            childMeasureWidth = child.getMeasuredWidth()
            childMeasureHeight = child.getMeasuredHeight()
            layoutWidth += childMeasureWidth //宽度累加
            if (childMeasureHeight > maxChildHeight) {
                maxChildHeight = childMeasureHeight
            }

            //确定子控件的位置，四个参数分别代表（左上右下）点的坐标值
            child.layout(R.attr.left, R.attr.top, R.attr.right, R.attr.bottom)
        }

    }
}